package ccnu.agile.utils;

import ccnu.agile.bean.entities.ProjectMemberRoleEntity;
import ccnu.agile.bean.entities.ResourceEntity;
import ccnu.agile.bean.entities.RoleEntity;
import ccnu.agile.bean.entities.RoleResourceEntity;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 权限控制工具类
 * @Author: JreamY
 * @Date: 2021/10/30
 **/
public class RBACUtils {

    private RBACUtils() {
    }

    private static List<RoleEntity> roleEntityList;
    private static List<ResourceEntity> resourceEntityList;
    private static List<RoleResourceEntity> roleResourceEntityList;

    private static List<ProjectMemberRoleEntity> projectMemberRoleEntityList;

    public static void init(
            List<RoleEntity> roList, List<ResourceEntity> reList,
            List<RoleResourceEntity> rrList, List<ProjectMemberRoleEntity> pmrList) {
        roleEntityList = roList;
        resourceEntityList = reList;
        roleResourceEntityList = rrList;
        projectMemberRoleEntityList = pmrList;
    }

    public static ProjectMemberRoleEntity findMemberRoleId(Integer userId) {

        if (!CollectionUtils.isEmpty(projectMemberRoleEntityList)) {
            for (ProjectMemberRoleEntity entity : projectMemberRoleEntityList) {
                if (entity.getUserId().equals(userId)) {
                    return entity;
                }
            }
        }
        return null;
    }

    public static List<RoleResourceEntity> findRoleResourceList(Integer roleId) {

        if (!CollectionUtils.isEmpty(roleResourceEntityList)) {
            List<RoleResourceEntity> resultList = new ArrayList<>();
            for (RoleResourceEntity entity : roleResourceEntityList) {
                if (entity.getRoleId().equals(roleId)) {
                    resultList.add(entity);
                }
            }
            return resultList;
        }
        return null;
    }

    public static ResourceEntity findNameResource(String name) {

        if (!CollectionUtils.isEmpty(resourceEntityList)) {
            for (ResourceEntity entity : resourceEntityList) {
                if (entity.getName().equals(name)) {
                    return entity;
                }
            }
        }
        return null;
    }
}
